package com.training.corejava.movie;

import java.util.List;
import java.util.Scanner;

public class MovieStore {

	public static void main(String[] args) {
		
		MovieLibrary library = new MovieLibrary();
		String movieTitle = null;
		String movieType = null;

		Scanner scanner = new Scanner(System.in);
		ShoppingCart cart = new ShoppingCart();

		System.out.println("Welcome to Blockbuster!!");
		System.out
				.println("Please enter your movie name,type (BlueRay/DVD) and number of days to rent in a comma separated way: ");
		System.out.println("Once you are done, type checkout and enter:\n");

		while (scanner.hasNextLine()) {
			String line = scanner.nextLine();

			if (line.equalsIgnoreCase("checkout")) {
				break;
			}

			String[] tokens = line.split(",");
			

			if (tokens.length < 3) {
				System.out.println("Invalid input provided: \n");

			} else {
				movieTitle = tokens[0];
				movieType = tokens[1];
				int numberOfDays = Integer.parseInt(tokens[2]);

				
				boolean inStock = library.inStock(movieTitle);

				if (!inStock) {
					System.out
							.println("Sorry, this movie is not available: \n");
				} else {
					cart.add(movieTitle, movieType, numberOfDays);
					

				}

			}

		}

		System.out
				.println("Type yes if have promocode or type  NO if you don't have promocode.");
		if (scanner.hasNext()) {
			Promotion promotion = null;
			boolean hasPromocode = false;

			String hasPromo = scanner.nextLine();

			if (hasPromo.equalsIgnoreCase("yes")) {
				hasPromocode = true;
			} else if (hasPromo.equalsIgnoreCase("no")) {
				hasPromocode = false;
			}

			if (hasPromocode == true) {
				System.out.println("Please enter your promotion code now..\n");
				if (scanner.hasNext()) {
					String promotionCode = scanner.next();

					try {
						promotion = new Promotions()
								.getPromotion(promotionCode);
						
					} catch (InvalidPromotionException e) {
						System.out
								.println("Sorry, but this promotion code is either not valid or expired.:\n");
						System.exit(0);
					}
					
				}
				
			}	
			
			
		
			InvoiceGenerator generator = new InvoiceGenerator();

			String invoice = generator.generate(cart.getRentals(), promotion);

			System.out.println("Please find below your invoice: \n");
			System.out.println(invoice);

			System.out
					.println(" Thanks for choosing Blockbuster.  Have a good day!!");
			
			library.deleteMovie(movieTitle, MovieType.valueOf(movieType));
			
			List<Movie> moviesLeft = MovieLibrary.getMovies();
			
			for (Movie movie : moviesLeft) {
				System.out.println(movie.getTitle() + "  " + movie.getMovieType());
			}		
			
			
			
			System.exit(0);
		}
		scanner.close();
		
	}
}
